
#include <QDebug>
#include "mywdigelayout.h"
#include <QVBoxLayout>
#include <QLineEdit>
#include <QSpacerItem>
#include <QMessageBox>
#include <QStandardItemModel>
#include <QSizePolicy>
#include <xlsxdocument.h>
#include <QFile>
#include <QFileDialog>
#include <QCoreApplication>
#include <QSettings>
#include <QTextCodec>
#include <QHeaderView>



MyWdigeLayout::MyWdigeLayout(Widget *parent)
{
    mPWidge = parent;
    mUi = mPWidge->GetUi();
}

bool MyWdigeLayout::CheckSetting(QSettings &settings)
{
    // 配置文件存在，读取配置项并进行校验
    bool allKeysExist = true;

    QStringList requiredKeys = {
        "customs_declaration_form_prefix_INSERT",
        "customs_declaration_form_prefix_CHECK",
        "user"
    };
    for (const QString &key : requiredKeys) {
        if (!settings.contains(key)) {
            allKeysExist = false;
            break;
        }
    }

    if (!allKeysExist) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setWindowTitle("配置项缺失提醒");
        msgBox.setText("配置文件中部分关键配置项缺失，请检查配置！不清楚请直接删除config.ini文件，重新打开工具会自动重新生成");
        msgBox.addButton(QMessageBox::Ok);
        //QObject::connect(&msgBox, &QMessageBox::accepted, qApp, &QCoreApplication::exit);
        msgBox.exec();
        while(1) {
            QCoreApplication::exit();
        }
        return false;
    }
    return true;

}

bool MyWdigeLayout::InitLoadFile()
{
    // 获取当前应用程序所在目录
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QString currentDir = QCoreApplication::applicationDirPath();
    QString configFilePath = currentDir + "/config.ini";

    QSettings settings(configFilePath, QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("utf-8"));
    // 检查配置文件是否存在，如果不存在则创建并写入默认配置
    if (!QFile::exists(configFilePath)) {
        // 创建配置文件所在目录（如果不存在）
        QDir dir(currentDir);
        if (!dir.exists()) {
            dir.mkpath(".");
        }

        // 报关单前缀
        settings.setValue("customs_declaration_form_prefix_INSERT", mFormPrefixInsert); //录入
        settings.setValue("customs_declaration_form_prefix_CHECK", mFormPrefixCheck);  // 核对
        // 设置默认的配置项值，这里假设多个报关员示例

        QString customsOfficersStr = mUserList.join(",");
        settings.setValue("User", customsOfficersStr);

        qDebug() << "已创建新的配置文件，并写入默认配置。";
    } else {
        if (!CheckSetting(settings)) {
            return false;
        }
        // 配置文件存在，读取配置项
        mFormPrefixInsert = settings.value("customs_declaration_form_prefix_INSERT").toString();
        mFormPrefixCheck = settings.value("customs_declaration_form_prefix_CHECK").toString();
        QString customsOfficersStr = settings.value("User").toString();
        mUserList.clear();
        mUserList = customsOfficersStr.split(",");

        qDebug() << "customs_declaration_form_prefix_INSERT: " << mFormPrefixInsert;
        qDebug() << "customs_declaration_form_prefix_CHECK: " << mFormPrefixCheck;
        qDebug() << "User: ";
        for (const QString &officer : mUserList) {
            qDebug() << officer;
        }
    }
    return true;
}


void MyWdigeLayout::InitLayout()
{
    QVBoxLayout *layout = new QVBoxLayout(mPWidge);
    // layout->setSpacing(0); // 设置布局之间的间距为0
    layout->setAlignment(Qt::AlignTop);

    InitFirstLayout(layout);
    InitSecondLayout(layout);

    InitThirdLayout(layout);

    InitForthLayout(layout);
    InitFifthLayout(layout);
    InitTableView(layout);

    InitButtonFun();
}

bool MyWdigeLayout::LoadXlsxFile(QString fileName)
{
    QXlsx::Document xlsx(fileName);
    QVector<QString> firstRowData;
    QXlsx::CellRange range = xlsx.dimension();
    // 从第一行的第一个单元格到第一行的最后一个单元格
    for (int col = 1; col <= range.columnCount(); ++col) {
        QXlsx::CellReference cell(1, col);
        QString cellValue = xlsx.read(cell).toString();
        // 跳过空或仅包含空格的单元格
        if (!cellValue.trimmed().isEmpty()) {
            firstRowData.append(cellValue);
        }
    }
    bool allFieldsExist = true;
    for (const QString& field : mExcelLineContext) {
        if (field.trimmed().isEmpty()) {
            continue;
        }
        if (!firstRowData.contains(field)) {
             QMessageBox::warning(nullptr, "Error", "文件读取失败，文件首行未找到字符串" + field + "请检查excel文件");
            allFieldsExist = false;
            break;
        }
    }

    if (allFieldsExist) {
        qDebug() << "The first row contains all fields.";

        // 创建一个 QStandardItemModel 作为 QTableView 的数据模型
        int numRows = range.rowCount();
        int numCols = range.columnCount();

        // 读取 Excel 文件中的数据并添加到 QStandardItemModel 中
        for (int row = 2; row <= numRows; ++row) {
            for (int col = 1; col <= numCols; ++col) {
                if (col > mTableModel->columnCount()) {
                    qDebug() << "Column index exceeds the maximum allowed columns.";
                    break;
                }
                QXlsx::CellReference cell(row, col);
                QString cellValue = xlsx.read(cell).toString();
                QStandardItem* item = new QStandardItem(cellValue);
                item->setTextAlignment(Qt::AlignCenter); // 设置单元格内容居中显示
                mTableModel->setItem(row - 2, col - 1, item); // 行索引减 2 以跳过第一行
            }
        }
    } else {
        qDebug() << "The first row does not contain all fields.";
        return false;
    }
    return true;
}


void MyWdigeLayout:: SetFilePath()
{
    qDebug() << "enter setFile";
    QString savefilePath = QFileDialog::getOpenFileName(nullptr, "选择文件");
    if (!savefilePath.isEmpty()) {
        mXlsxFilePath->setText(savefilePath);
    }
    qDebug() << "set file path" + mXlsxFilePath->text();
    QFile file(mXlsxFilePath->text());
    if (file.exists()) {
        qDebug() << "load file " + mXlsxFilePath->text();
        LoadXlsxFile(mXlsxFilePath->text());
    }
}


void MyWdigeLayout::saveToFile(const QString& fileName) {
    QXlsx::Document xlsx;
    int numRows = mTableModel->rowCount();
    int numCols = mTableModel->columnCount();

    // 先写入标题行
    for (int col = 0; col < numCols; ++col) {
        QStandardItem* item = mTableModel->horizontalHeaderItem(col);
        if (item) {
            xlsx.write(1, col + 1, item->text());
        } else {
            xlsx.write(1, col + 1, "");
        }
    }

    for (int row = 0; row < numRows; ++row) {
        for (int col = 0; col < numCols; ++col) {
            QStandardItem* item = mTableModel->item(row, col);
            if (item) {
                xlsx.write(row + 2, col + 1, item->text());
            } else {
                // 如果单元格为空，写入空字符串
                xlsx.write(row + 2, col + 1, "");
            }
        }
    }
    xlsx.saveAs(fileName);
}

void MyWdigeLayout::ReGenExeclFile()
{
    QString fileName = mXlsxFilePath->text();
    QFile file(fileName);

    if (file.exists()) {
        QMessageBox::StandardButton reply = QMessageBox::question(mPWidge, "File Exists", "excel已存在. 点击确定将覆盖保存",
                                                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton);
        if (reply == QMessageBox::Yes) {
            saveToFile(fileName);
        }
    } else {
        QMessageBox::StandardButton reply = QMessageBox::question(mPWidge, "Save File", "未检测到已有文件. 是否新增文件保存?",
                                                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton);
        if (reply == QMessageBox::Yes) {
            saveToFile(fileName);
        }
    }
}

void MyWdigeLayout::InitFirstLayout(QVBoxLayout *layout)
{
    mLabelMap.insert(0,new QLabel("客户"));
    mLabelMap.insert(1,new QLabel("日期"));
    mLabelMap.insert(2,new QLabel("报关单号-出口"));
    mLabelMap.insert(3,new QLabel("报关单号-进口"));
    mLabelMap.insert(4,new QLabel("核注清单1"));
    mLabelMap.insert(5,new QLabel("核注清单2"));


    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addItem(new QSpacerItem(240, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    for (auto it : mLabelMap) {
        // it->setMinimumHeight(30); // 设置最小高度
        // it->setMaximumHeight(30); // 设置最大高度
        it->setMinimumWidth(100); // 设置最小宽度
        it->setMaximumWidth(100); // 设置最大宽度
        topLayout->addWidget(it);
        topLayout->addItem(new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
        //topLayout->addSpacing(50);

    }
    topLayout->addStretch(1);
    topLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(topLayout);
}

void MyWdigeLayout::InitSecondLayout(QVBoxLayout *layout)
{
    for (uint32_t i = EMU_USER_NAME; i < EMU_CONTEXT_LINE_EDIT_MAX; ++i) {
        mLineEditMap.insert(i, new QLineEdit());
    }
    QHBoxLayout *tmpLayout = new QHBoxLayout;

    tmpLayout->addItem(new QSpacerItem(130, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    for (auto it : mLineEditMap) {
        it->setMinimumWidth(100); // 设置最小宽度
        it->setMaximumWidth(100); // 设置最大宽度
        tmpLayout->addItem(new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
        tmpLayout->addWidget(it);

    }
    tmpLayout->addStretch(1);
    tmpLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(tmpLayout);
    // 添加一个空行
    QSpacerItem *spacer = new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum);
    layout->addItem(spacer);
}


void MyWdigeLayout::InitThirdLayout(QVBoxLayout *layout)
{
    QMap<uint32_t, QLabel*> LabelMap;

    LabelMap.insert(EMU_USER_LIST_SLIPS, new QLabel("客户清单"));
    LabelMap.insert(EMU_LIST_SLIPS, new QLabel("清单"));
    LabelMap.insert(EMU_VERIFICATION_SLIPS, new QLabel("核放单"));
    LabelMap.insert(EMU_CUSTOMS_DECLARTION, new QLabel("报关单"));
    LabelMap.insert(EMU_EMU_INSERT_OPERATOR_USR, new QLabel("操作人"));


    QHBoxLayout *tmpLayout = new QHBoxLayout;
    tmpLayout->addItem(new QSpacerItem(160, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    for (auto it : LabelMap) {
        tmpLayout->addItem(new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
        it->setMinimumWidth(100); // 设置最小宽度
        it->setMaximumWidth(100); // 设置最大宽度
        tmpLayout->addWidget(it);

    }
    tmpLayout->addStretch(1);
    tmpLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(tmpLayout);

}

void MyWdigeLayout::InitForthLayout(QVBoxLayout *layout)
{
    for (int combboxEmu = EMU_USER_LIST_SLIPS; combboxEmu < EMU_CHECK_LIST_SLIPS; combboxEmu++) {
        mLineEditListContentMap.insert(combboxEmu, new QLineEdit());
    }
    for (int combboxEmu = EMU_CHECK_LIST_SLIPS; combboxEmu < EMU_EMU_INSERT_OPERATOR_USR; combboxEmu++) {
        mLineEditCheckContentMap.insert(combboxEmu, new QLineEdit());
    }

    qInfo() << "init combobox user " << mUserList;
    for (auto it : mLineEditListContentMap) {
        it->setMinimumHeight(30); // 设置最小高度
        it->setMaximumHeight(30); // 设置最大高度
        it->setMinimumWidth(100); // 设置最小宽度
        it->setMaximumWidth(100); // 设置最大宽度
        //it->addItems(mUserList);
    }
    for (auto it : mLineEditCheckContentMap) {
        it->setMinimumHeight(30); // 设置最小高度
        it->setMaximumHeight(30); // 设置最大高度
        it->setMinimumWidth(100); // 设置最小宽度
        it->setMaximumWidth(100); // 设置最大宽度
        //it->addItems(mUserList);
    }

    mInsertUsrComb = new QComboBox();
    mInsertUsrComb->addItems(mUserList);

    mCheckUsrComb = new QComboBox();
    mCheckUsrComb->addItems(mUserList);


    QHBoxLayout *secondLayout = new QHBoxLayout;
    secondLayout->addItem(new QSpacerItem(200, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    secondLayout->addWidget(new QLabel("录入"));

    QHBoxLayout *thirdLayout = new QHBoxLayout;
    thirdLayout->addItem(new QSpacerItem(200, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    thirdLayout->addWidget(new QLabel("核对"));

    for (auto it = mLineEditListContentMap.begin(); it != mLineEditListContentMap.end(); ++it) {
        //qInfo() << "key " << it.key() << "max： " << EMU_CONTEXT_MAX / 2;
        secondLayout->addWidget(it.value());
        secondLayout->addItem(new QSpacerItem(98, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    }

    secondLayout->removeItem(secondLayout->itemAt(secondLayout->count() - 1));
    secondLayout->addItem(new QSpacerItem(120, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    secondLayout->addWidget(mInsertUsrComb);

    thirdLayout->addItem(new QSpacerItem(204, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    for (auto it = mLineEditCheckContentMap.begin(); it != mLineEditCheckContentMap.end(); ++it) {
        thirdLayout->addWidget(it.value());
        thirdLayout->addItem(new QSpacerItem(302, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    }
    thirdLayout->removeItem(thirdLayout->itemAt(thirdLayout->count() - 1));
    thirdLayout->addItem(new QSpacerItem(120, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));


    thirdLayout->addWidget(mCheckUsrComb);
    secondLayout->addStretch(1);
    thirdLayout->addStretch(1);


    secondLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    thirdLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(secondLayout);
    layout->addLayout(thirdLayout);
}

void MyWdigeLayout::InitFifthLayout(QVBoxLayout *layout)
{

    QHBoxLayout *forthLayout = new QHBoxLayout;

    forthLayout->addItem(new QSpacerItem(200, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    auto label = new QLabel("excel文件名");
    forthLayout->addWidget(label);
    forthLayout->addSpacing(20);

    //forthLayout->addItem(new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
    mXlsxFilePath = new QLineEdit();
    mXlsxFilePath->setFixedWidth(500);

    forthLayout->addWidget(mXlsxFilePath);
    //forthLayout->addSpacing(20);  // 添加固定大小为20像素的间隙
    //forthLayout->addItem(new QSpacerItem(100, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));

    QPushButton* btSel = new QPushButton("加载文件");
    QPushButton* btAdd = new QPushButton("增加");
    QPushButton* btDel = new QPushButton("删除");
    QPushButton* btGenerate = new QPushButton("重新生成excel");
    mButtonMap.insert(EMU_SELECT_FILE, btSel);
    mButtonMap.insert(EMU_ADD_DATA, btAdd);
    mButtonMap.insert(EMU_DEL_DATA, btDel);
    mButtonMap.insert(EMU_GENERATE_FILE, btGenerate);

    for (uint32_t i = EMU_SELECT_FILE; i < EMU_BUTTON_MAX; ++i) {
        // it->setMinimumHeight(30); // 设置最小高度
        // it->setMaximumHeight(30); // 设置最大高度
        mButtonMap[i]->setMinimumWidth(70); // 设置最小宽度
        mButtonMap[i]->setMaximumWidth(150); // 设置最大宽度
        forthLayout->addWidget(mButtonMap[i]);
        forthLayout->addItem(new QSpacerItem(80, 30, QSizePolicy::Fixed, QSizePolicy::Minimum));
        //topLayout->addSpacing(50);

    }
    forthLayout->addStretch(1);

    forthLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(forthLayout);
}

void MyWdigeLayout::InitTableView(QVBoxLayout *layout)
{

    // 创建一个QScrollArea
    QScrollArea *scrollArea = new QScrollArea();
    // 创建一个 QTableView
    mTableView = new QTableView(scrollArea);
    mTableView->setFixedSize(2000, 300);

    // 设置表格视图为只读
    //mTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);


    // 创建一个QStandardItemModel
    mTableModel = new QStandardItemModel(0, mExcelLineContext.size());

    // 设置表头


    for (uint8_t i = 0; i < mExcelLineContext.size(); ++i) {
        mTableModel->setHorizontalHeaderItem(i, new QStandardItem(mExcelLineContext[i]));
    }


    // 设置模型
    mTableView->setModel(mTableModel);

    //mTableView->resizeColumnsToContents();
    mTableView->setColumnWidth(2, 150);
    mTableView->setColumnWidth(3, 150);

    scrollArea->setAlignment(Qt::AlignRight);
    // 将QTableView添加到QScrollArea中
    scrollArea->setWidget(mTableView);
    QHBoxLayout *fifthLayout = new QHBoxLayout;

    //fifthLayout->addWidget(mTableView);
    fifthLayout->addWidget(scrollArea);
    fifthLayout->setAlignment(Qt::AlignHCenter); // 设置对齐方式
    layout->addLayout(fifthLayout);
    mPWidge->SetTabView(mTableView);
}


void MyWdigeLayout::InitExcelFile()
{
    if (!QFile::exists(mFileName)) {
        qInfo() << "not find file" << mFileName;
        QXlsx::Document xlsx(mFileName);
        int columnCount = mTableModel->columnCount();
        for (int i = 0; i < columnCount; ++i) {
            QString header = mTableModel->horizontalHeaderItem(i)->text();
            qInfo() << "write" << header;
            xlsx.write(1, i + 1, header);
        }
        xlsx.save();
    } else {
        qInfo() << "has find file" << mFileName;
    }
}

bool MyWdigeLayout::CheckFileAccessible()
{
    mFileName = mXlsxFilePath->text();
    if (mFileName.isEmpty()) {
        QMessageBox::warning(mPWidge, "错误", "请先设置保存的excel文件名！", QMessageBox::Yes);
        return false;
    }

    if(!mFileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        QMessageBox::warning(mPWidge, "错误", "excel文件名需要以.xlsx结尾", QMessageBox::Yes);
        return false;
    }

    InitExcelFile();
    QFile file(mFileName);
    if (!file.open(QIODevice::Append | QIODevice::Text)) {
        QMessageBox::warning(mPWidge, "错误", "文件正在被其他程序使用，先关闭文件！", QMessageBox::Yes);
        return false;
    }
    return true;
}


bool MyWdigeLayout::CheckInsertData()
{
    QString searchString = mFormPrefixInsert + mLineEditMap[EMU_CUSTOMS_DECLARTION_OUT]->text();  // 报关单出口
    QString searchString2 = mFormPrefixCheck + mLineEditMap[EMU_CUSTOMS_DECLARTION_IN]->text();  // 报关单进口

    for (int row = 0; row < mTableModel->rowCount(); ++row) {
        QStandardItem *itemout = mTableModel->item(row, EMU_CUSTOMS_DECLARTION_OUT);  // 获取第一列的项
        QStandardItem *itemin = mTableModel->item(row, EMU_CUSTOMS_DECLARTION_IN);  // 获取第一列的项

        if (itemout && (!itemout->text().isEmpty()) &&
            (itemout->text() == searchString)) {
            QMessageBox::information(mPWidge, "信息", "报关单-出口重复！");
            return false;
        }
        if (itemin && (!itemin->text().isEmpty()) &&
            (itemin->text() == searchString2)) {
            QMessageBox::information(mPWidge, "信息", "报关单-进口重复！");
            return false;
        }
    }

    return true;
}

void MyWdigeLayout::InitButtonFun()
{
    if (mButtonMap[EMU_ADD_DATA] == nullptr ||
        mButtonMap[EMU_DEL_DATA] == nullptr ||
        mButtonMap[EMU_SELECT_FILE] == nullptr ||
        mButtonMap[EMU_GENERATE_FILE] == nullptr) {
        qInfo() << "button is empty";
    }
    QObject::connect(mButtonMap[EMU_ADD_DATA], &QPushButton::clicked, this, &MyWdigeLayout::onAddButtonClicked);
    QObject::connect(mButtonMap[EMU_DEL_DATA], &QPushButton::clicked, this, &MyWdigeLayout::onDelButtonClicked);
    QObject::connect(mButtonMap[EMU_SELECT_FILE], &QPushButton::clicked, this, &MyWdigeLayout::SetFilePath);
    QObject::connect(mButtonMap[EMU_GENERATE_FILE], &QPushButton::clicked, this, &MyWdigeLayout::ReGenExeclFile);

}

void MyWdigeLayout::onAddButtonClicked()
{
    if (CheckFileAccessible() == false) {
        return;
    }
    if (CheckInsertData() == false) {
        return;
    }

    QVector<QString> rawValueVec;
    for (auto it =  mLineEditMap.begin(); it != mLineEditMap.end() && it.key() < EMU_CHECK_LIST_1; ++it) {
        if (it.key() == EMU_CUSTOMS_DECLARTION_OUT && !it.value()->text().isEmpty()) {
            rawValueVec.push_back(mFormPrefixInsert + it.value()->text());
        } else if (it.key() == EMU_CUSTOMS_DECLARTION_IN && !it.value()->text().isEmpty()) {
            rawValueVec.push_back(mFormPrefixCheck + it.value()->text());

        }else {
            rawValueVec.push_back(it.value()->text());
        }
    }

    for (auto it : mLineEditListContentMap) {
        rawValueVec.push_back(it->text());
    }
    rawValueVec.push_back(mInsertUsrComb->currentText());
    rawValueVec.push_back(" ");

    for (auto it : mLineEditCheckContentMap) {
        rawValueVec.push_back(it->text());
    }


    rawValueVec.push_back(mCheckUsrComb->currentText());
    rawValueVec.push_back(" ");

    for (auto it = mLineEditMap.find(EMU_CHECK_LIST_1); it != mLineEditMap.end(); ++it) {
        rawValueVec.push_back(it.value()->text());
    }
    // 创建新行
    QList<QStandardItem*> newRow;
    for (auto it : rawValueVec) {
        qInfo() << "text is " << it;
        auto newItem = new QStandardItem(it);
        newItem->setTextAlignment(Qt::AlignCenter); // 设置文本居中
        newRow.append(newItem);

    }
    qInfo() << "newrow size" << newRow.size();
    if(mTableModel == nullptr) {
        qInfo() << "mTableModel is null";
    }
    mTableModel->appendRow(newRow);


    QXlsx::Document xlsx(mFileName);
    int xlsxRow = xlsx.dimension().rowCount() + 1;
    qInfo() << "xlsx line " << xlsxRow << "col:" << mTableModel->columnCount();
    int columnCount = mTableModel->columnCount();
    int rowCount = mTableModel->rowCount();

    for (int i = 0; i < columnCount && rowCount >= 1; ++i) {
        QString data = mTableModel->item(rowCount - 1, i)->text();
        qInfo() << "data is " << data;
        xlsx.write(xlsxRow, i + 1, data);
    }
    xlsx.save();
}

void MyWdigeLayout::onDelButtonClicked()
{
    qInfo() << "删除";
    //QString strDelList;
    QItemSelectionModel *selectionModel = mTableView->selectionModel();
    if (selectionModel->hasSelection()) {
        qInfo() << "has select";
        QModelIndexList selectedRows = selectionModel->selectedRows();
        qInfo() << "has select row" << selectedRows;

        foreach (QModelIndex index, selectedRows) {
            int row = index.row();
            if (QMessageBox::question(mPWidge, "确认删除", QString("是否删除选中行 %1？").arg(row + 1), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
                mTableModel->removeRow(row);
                //strDelList = mTableModel->item(row, 2)->text();  // 获取第3列的项
            }

        }
    } else {
        QMessageBox::warning(mPWidge, "警告", "没有选中任何行！");
    }

    // if (!strDelList.isEmpty()) {
    //     if (QMessageBox::question(mPWidge, "确认删除", QString("是否同时删除excel中报关单-出口 %1？").arg(strDelList), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
    //         if (CheckFileAccessible()) {

    //         } else {
    //             return;
    //         }
    //     }
    // }

}


